package com.dc.es;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@SpringBootTest
public class TESTs {

    @Test
    public void  test1(){
        // 创建线程池，corePoolSize 为 2，maximumPoolSize 为 5，队列大小为 10
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                2, // corePoolSize
                5, // maximumPoolSize
                60L, // keepAliveTime
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(10), // workQueue capacity
                new ThreadPoolExecutor.AbortPolicy() // rejection handler
        );

        // 模拟提交多个任务
        for (int i = 0; i < 20; i++) {
            final int taskNumber = i;
            try {
                executor.execute(() -> {
                    System.out.println("Executing task " + taskNumber + " by " + Thread.currentThread().getName());
                    try {
                        // 模拟任务处理时间
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                });
            } catch (RejectedExecutionException e) {
                System.err.println("Task " + taskNumber + " was rejected: " + e.getMessage());
            }
        }

        // 关闭线程池
        executor.shutdown();
        try {
            // 等待所有任务完成
            if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                executor.shutdownNow(); // 取消当前执行的任务
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
        }
    }

}
